import express from 'express';
import Ret, { RetCode } from '../../../bean/code/Ret';
import logger from '../../../utils/logger';
const app = express();
import request from 'request'
import { urlEncode } from '../../../utils/index';
import ConfigReader from '../../../utils/configReader';
import { db, Sequelize } from '../../../dao/config/index';
const { appid, secret } = new ConfigReader("./server/config/wechat.json").get("dev");
const User = require("../../../dao/models/f_user")(db, Sequelize);
const UserRealInfo = require("../../../dao/models/f_user_real_info")(db, Sequelize);

User.hasOne(UserRealInfo, {
    foreignKey: "user_id"
})

/**
 * 获取openId
 */
app.post("/getOpenIdByCode", async (req, res) => {
    const { code } = req.body;
    const params = {
        secret,
        appid,
        js_code: code,
        grant_type: "authorization_code"
    }
    request(`https://api.weixin.qq.com/sns/jscode2session${urlEncode(params)}`, async function (error, response, body) {
        if (!error && response.statusCode == 200) {
            // 判断该用户是否存在 存在则返回 不存在则创建
            const wxRes = JSON.parse(body);
            const { openid } = wxRes;
            if (!openid) throw new Error("code换取openid失败！");
            await User.findOrCreate({ where: { openid }, default: { openid } });
            res.json(Ret(RetCode.SUCCESS).setData(wxRes));
        }
    })
})

/**
 * 登录
 */
app.post("/login", async (req, res) => {
    const userInfo = req.body;
    const { openid: openid } = userInfo;
    const userModel = await User.find({ where: { openid }, include: UserRealInfo });
    // 如果已有推荐人则不更新推荐人字段
    const recommenderId = userModel.recommenderId;
    if (recommenderId) delete userInfo.recommenderId;
    const resData = await userModel.update(userInfo);

    res.json(Ret(RetCode.SUCCESS).setData(userModel));
})


export default app;
